/**
 * Copyright 2010, Lars J. Nilsson <http://www.larsan.net> 
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.larsan.dconf.jbc;

import static org.apache.commons.lang.Validate.notNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.larsan.dconf.DNode;
import net.larsan.dconf.DNodeSpi;
import net.larsan.dconf.DPath;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.jboss.cache.Node;

public class JBCNode extends DNodeSpi {
	
	public static DNode toJbcNode(JBCNodeStore store, DPath path, Node<String, String> node) {
		return node == null ? null : new JBCNode(store, path, node);
	}
	
	public static DNode toJbcNode(JBCNodeStore store, Node<String, String> node) {
		return node == null ? null : new JBCNode(store, new PathNormalizer().fromJbc(node.getFqn().toString()), node);
	}
	
	public static List<DNode> toJdbcNodeList(JBCNodeStore store, Set<Node<String, String>> real) {
		if(real == null) return null;
		List<DNode> nodes = new ArrayList<DNode>(real.size());
		for (Node<String, String> n : real) {
			nodes.add(toJbcNode(store, n));
		}
		return nodes;
	}
	
	private final Node<String, String> internal;

	protected JBCNode(JBCNodeStore store, DPath path, Node<String, String> internal) {
		super(store, path);
		notNull(internal);
		this.internal = internal;
	}

	@Override
	protected List<DNode> spiGetChildren() {
		return toJdbcNodeList((JBCNodeStore)store, internal.getChildren());
	}

	@Override
	protected DNode spiGetParent(DPath p) {
		return toJbcNode((JBCNodeStore)store, p, internal.getParent());
	}

	@Override
	protected Map<String, String> spiGetAttributes() {
		return internal.getData();
	}
	
	
	// --- COMMON OBJECT METHODS --- //
	
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}
	
	@Override
	public boolean equals(Object o) {
		return EqualsBuilder.reflectionEquals(this, o);
	}
	
	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}
}
